import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:fate_blind_box/chat_view/dialog/utils.dart';
import 'package:fate_blind_box/chat_view/video_push_widget.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/ui/Home/map/near_by_map_view/near_by_map_page.dart';
import 'package:fate_blind_box/utils/map/map_common_config.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:permission_handler/permission_handler.dart';

import 'state.dart';

class MeetHomeLogic extends GetxController {
  final MeetHomeState state = MeetHomeState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    state.controller.addListener(() {
      state.rollHeight.value = state.controller.position.pixels;
      // 根据滚动位置设置透明度
      if (state.controller.position.pixels <= 0) {
        state.opacity.value = 0;
        state.pinned.value = false;
      } else if (state.controller.position.pixels > 0 &&
          state.controller.position.pixels < 160.w) {
        state.opacity.value = state.controller.position.pixels / 160.w < 1
            ? state.controller.position.pixels / 160.w
            : 1;
        state.pinned.value = false;
      } else if (state.controller.position.pixels > 310.w) {
        state.pinned.value = true;
      } else {
        state.pinned.value = false;
      }
    });
    _getUserInfo();
    _getList();
    // 初始化定位
    _initHomeLocation();
    checkLoc();
  }

  /// 检查定位权限
  Future<bool> isOpenLocationPermission() async {
    var status = await Permission.location.status;
    if (status.isGranted) {
      return false;
    }
    return true;
  }

  /// 获取用户信息
  _getUserInfo() async {
    EasyLoading.show();
    final res = await Api.getInstance().getMemberInfo(Provider.memberId);
    EasyLoading.dismiss();
    if (res['code'] == 0) {
      final data = res['data'];
      state.realSex = data['realSex'];
    } else {
      ThemeSnackBar.show(Get.context!, res['msg']);
    }
  }

  /// 获取红娘列表
  _getList() async {
    final res = await Api.getInstance().getMatchmakerList(1000, 1);
    if (res['code'] == 0) {
      final data = res['data'];
      if (data != null) {
        List list = data['list'];
        if (list.isNotEmpty == true) {
          state.matchmakerList.addAll(list);
          state.matchmakerList.refresh();
        }
      }
    } else {
      ThemeSnackBar.show(Get.context!, res['msg']);
    }
  }

  /// 定位
  _initHomeLocation() {
    state.homeMainController.markList = [];
    state.homeMainController.getMapShopList(0.000000, 0.000000);
    EMClient.getInstance.userInfoManager.fetchOwnInfo();
  }

  // 权限检查
  checkLoc() async {
    if (Platform.isAndroid) {
      PermissionStatus status = await PermissionCheck.checkLocationPermission();
      if (status != PermissionStatus.granted) {
        var value = await permissionDialog(
          Get.context!,
          title: "“都肆商圈”需要使用您的位置权限，是否允许？",
          content: '不允许将无法为您提供定位服务',
        );
        if (value != '允许') {
          return;
        }
      }
    }

    /// 动态申请定位权限
    var status = await Permission.location.request();
    if (status == PermissionStatus.permanentlyDenied && Platform.isAndroid) {
      PermissionUtil.showDeniedDialog(Get.context!);
    } else if (status == PermissionStatus.granted) {
      getCurrentLocation();
    }
  }

  /// 获取当前定位
  void getCurrentLocation() async {
    /// [hasShow] 隐私权政策是否弹窗展示告知用户
    AMapFlutterLocation.updatePrivacyShow(true, true);

    /// [hasAgree] 隐私权政策是否已经取得用户同意
    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.setApiKey(
        MapCommonConfig.androidKey, MapCommonConfig.iosMapKey);

    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    _startLocation();

    ///注册定位结果监听
    state.locationListener = state.locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      double latitude = double.parse(result['latitude'].toString());
      double longitude = double.parse(result['longitude'].toString());
      state.homeMainController.getMapShopList(longitude, latitude);
    });
  }

  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await state.locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
    } else {}
  }

  ///开始定位
  void _startLocation() {
    ///开始定位之前设置定位参数
    _setLocationOption();
    state.locationPlugin.startLocation();
  }

  ///设置定位参数
  void _setLocationOption() {
    AMapLocationOption locationOption = AMapLocationOption();

    ///是否单次定位
    locationOption.onceLocation = true;

    ///是否需要返回逆地理信息
    locationOption.needAddress = true;

    ///逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.DEFAULT;

    locationOption.desiredLocationAccuracyAuthorizationMode =
        AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

    locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

    ///设置Android端连续定位的定位间隔
    locationOption.locationInterval = 2000;

    locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

    ///设置iOS端的定位最小更新距离<br>
    locationOption.distanceFilter = -1;

    locationOption.desiredAccuracy = DesiredAccuracy.HundredMeters;

    ///设置iOS端是否允许系统暂停定位
    locationOption.pausesLocationUpdatesAutomatically = false;

    ///将定位参数设置给定位插件
    state.locationPlugin.setLocationOption(locationOption);
  }

  /// 页面跳转
  void jumpNearByView({String titleName = '单身驿站'}) async {
    final status = await Permission.location.status;
    if (status.isGranted) {
      Get.to(NearByMapPage(
        pointMarkList: state.homeMainController.markList,
        titleStr: titleName,
        locationBack: (latitude, longitude, res) {
          state.homeMainController.starLon = longitude;
          state.homeMainController.starLat = latitude;
          state.homeMainController.saddress = res['address'] ?? '';
        },
      ));
    } else {
      if (Platform.isAndroid) {
        var value = await permissionDialog(
          Get.context!,
          title: "“都肆商圈”需要使用您的位置权限，是否允许？",
          content: '不允许将无法为您提供定位服务',
        );
        if (value != '允许') {
          return;
        }
      }
      var status = await Permission.location.request();
      if (status == PermissionStatus.permanentlyDenied) {
        PermissionUtil.showDeniedDialog(Get.context!);
      } else if (status == PermissionStatus.granted) {
        Get.to(NearByMapPage(
          pointMarkList: state.homeMainController.markList,
          titleStr: titleName,
          locationBack: (latitude, longitude, res) {
            state.homeMainController.starLon = longitude;
            state.homeMainController.starLat = latitude;
            state.homeMainController.saddress = res['address'] ?? '';
          },
        ));
      }
    }
  }
}
